﻿using IM.Easy.Core.Cache;
using IM.Easy.Core.ServiceLifetime;
using IM.Easy.Core.Services;
using IM.Easy.CoreServices.IServices;
using IM.Easy.Entity.System;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.CoreServices.Service
{
    /// <summary>
    /// 字典全局服务---必须保证是单例注入
    /// </summary>
    public class DictGlobalService(ISqlSugarClient db) : ISingleton, IDictGlobalService
    {
        private readonly ISqlSugarClient db = db;


        /// <summary>
        /// 配置全局字典---配置到缓存中
        /// </summary>
        public void SetGlobalData()
        {
            var dicts = db.Queryable<SysDictType>()
                         .Includes(s => s.Items)
                         .ToList();

            foreach (var dict in dicts)
            {
                CacheManager.Set($"dict:{dict.Code}", dict);
            }
        }

        /// <summary>
        /// 获取字典值
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public List<SysDictData> GetDictDatas(string code)
        {
            var type = CacheManager.Get<SysDictType>($"dict:{code}");
            return type.Items;
        }

        /// <summary>
        /// 获取字典文本值
        /// </summary>
        /// <param name="value"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetDictLabel(string value, string code)
        {
            var type = CacheManager.Get<SysDictType>($"dict:{code}");
            var label = type.Items.Where(s => s.Value == value).Select(s => s.Label).FirstOrDefault();
            return label;
        }

        /// <summary>
        /// 更新字典
        /// </summary>
        public void UpdateOrAppendDict(SysDictType dict)
        {
            CacheManager.Set($"dict:{dict.Code}", dict);
        }

        /// <summary>
        /// 移除字典
        /// </summary>
        /// <param name="code"></param>
        public void RemoteDict(string code)
        {
            CacheManager.Remove($"dict:{code}");
        }

        /// <summary>
        /// 刷新清空字典缓存
        /// </summary>
        public void Clear()
        {
            CacheManager.RemoveByPattern("dict:*");
        }
    }
}
